package com.abu.message.listener;

import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.TimeoutUtils;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RemoveNoticeListener {

    //    缓存中的公告数据指定的前缀
    private static final String NOTICE_PREFIX = "NOTICE_PREFIX:";

    //    交换机
    private static final String NOTICE_EXCHANGE = "NOTICE_EXCHANGE";
    //    路由键
    private static final String NOTICE_ROUTING_KEY = "NOTICE_ROUTING_KEY";

    @Autowired
    private StringRedisTemplate redisTemplate;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "DELETE_REDIS_NOTICE_DATA", durable = "true"),
            exchange = @Exchange(value = NOTICE_EXCHANGE, durable = "true", ignoreDeclarationExceptions = "true"),
            key = {NOTICE_ROUTING_KEY}
    ))
    public void deleteRedisNoticeData(Long noticeId) throws InterruptedException {
        if (noticeId != null) {
//        获取缓存的id
            String prefix = NOTICE_PREFIX + noticeId;
//        删除缓存直至成功
            boolean flag = false;
            do {
                flag = this.redisTemplate.delete(prefix);
//                删除失败，阻塞5分钟，五分钟后再次尝试执行删除
                if (!flag) {
                    TimeUnit.MINUTES.sleep(5);
                    System.out.println("delete loop...");
                }
                System.out.println("delete success...");
            } while (!flag);

        }
    }
}
